﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.WindowsAPICodePack.Shell;

namespace AutoCadConvert
{
    /// <summary>
    /// Interaction logic for DwgItem.xaml
    /// </summary>
    public partial class DwgItem : UserControl
    {
        ////图例属性
        public string m_TabName = "";

        public static Dictionary<string, string> s_CurrentDwgAttrib=new Dictionary<string, string>();
        public static string s_CurrentDwgFile = "";
        public static bool s_bCommandEnd = true;

        public UIElementCollection Children
        {
            get { return pannel.Children; }
        }
        public DwgItem()
        {
            InitializeComponent();
        }
        public void ClearState()
        {
            foreach (UIElement ui in pannel.Children)
                ((ui as StackPanel).Children[0] as Border).BorderThickness = new Thickness(0);
        }
        public void GetModelMaterial(string typeCode, ComboBox box)
        {
            Task.Factory.StartNew(new Action(() =>
            {
                HttpManager.CatalogLevel_Response ret = HttpManager.Catalog_Level(typeCode, "material");
                if (ret != null && ret.data.catalogs != null)
                {
                    box.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        box.ItemsSource = new string[] { "全部" }.Concat(ret.data.catalogs.Select(o => o.name));
                    }));
                }
            }));
        }
        public void GetAllChildLevel(HttpManager.CatalogLevel_Response.Catalog[] catalog,string classify,List<string> childTypeCode)
        {
            foreach (HttpManager.CatalogLevel_Response.Catalog item in catalog)
            {
                childTypeCode.Add(item.code);
                if (item.hasNext)
                {
                    HttpManager.CatalogLevel_Response ret = HttpManager.Catalog_Level(item.code, classify);
                    if (ret != null && ret.data.catalogs != null)
                    {
                        GetAllChildLevel(ret.data.catalogs, classify, childTypeCode);
                    }
                }
            }
        }
        public void FilterModel(IEnumerable<string> typeCodes)
        {//过滤图例信息
            try
            {
                foreach (UIElement ui in pannel.Children)
                {
                    if (ui is StackPanel)
                    {
                        string tagContent = (ui as StackPanel).Tag as string;
                        if (!typeCodes.Contains(tagContent.Split(new char[] { ';' })[4]))
                            ui.Visibility = Visibility.Collapsed;
                        else
                            ui.Visibility = Visibility.Visible;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);
            }
        }
        public void DownDwgFile(string typeCode, string classify,string tabName)
        {
            m_TabName = tabName;
            Task.Factory.StartNew(new Action(() =>
            {
                DownloadFile(typeCode, classify, 1, new List<string>());
            }));
        }
        private void DownloadFile(string typeCode, string classify, int page, List<string> allType)
        {
            //创建文件夹
            string fileDirectory = LoginInfo.instance().dwgFileDirectory;
            if (!Directory.Exists(fileDirectory))
                Directory.CreateDirectory(fileDirectory);

            HttpManager.LegendSearch_Response ls = HttpManager.Legend_Search(typeCode, classify, page);
            if (ls != null && ls.data.legends != null)
            {
                IEnumerable<HttpManager.LegendSearch_Response.Legend> filter;
                if (classify == "type1")
                {
                    if (m_TabName == "门窗")
                        filter = ls.data.legends.Where(o => o.name.Contains("门") || o.name.Contains("窗"));
                    else
                        filter = ls.data.legends.Where(o => !o.name.Contains("门") && !o.name.Contains("窗"));
                }
                else
                {
                    filter = ls.data.legends;
                }
                //记录数据
                allType.AddRange(filter.Select(o=>o.typeCode.Last()));
                WebClient client = new WebClient();
                foreach (HttpManager.LegendSearch_Response.Legend legend in filter)
                {
                    string newFile = System.IO.Path.Combine(fileDirectory, legend.sn + ".dwg");
                    if (!FindDwgSn(legend.sn))
                    {
                        if (!File.Exists(newFile))
                            client.DownloadFile(legend.dwgUrl, newFile);
                        AddDwgResource(newFile, legend, m_TabName);
                    }
                }
                if (ls.data.count > ls.data.legends.Count() + (page - 1) * 10)
                {
                    DownloadFile(typeCode, classify, page + 1, allType);
                }
                else
                {
                    this.Dispatcher.BeginInvoke(new Action(()=> {
                        foreach (UIElement ui in pannel.Children)
                        {
                            if (ui is StackPanel)
                            {
                                string tagContent = (ui as StackPanel).Tag as string;
                                if (!allType.Contains(tagContent.Split(new char[] { ';' })[4]))
                                    ui.Visibility = Visibility.Collapsed;
                                else
                                    ui.Visibility = Visibility.Visible;
                            }
                        }
                    }));
                }
            }
        }
        public void AddDwgResource(string file, HttpManager.LegendSearch_Response.Legend legend,string tabName)
        {
            BitmapSource bs = WindowsThumbnailProvider.WfGetSource(file);
            //ShellFile shellFile = ShellFile.FromFilePath(file);
            //BitmapSource bs = shellFile.Thumbnail.BitmapSource;
            bs.Freeze();
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                Border border = new Border();
                border.BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(32, 184, 226));
                border.Width = tabName == "search" ? 115 : 90;
                border.Height = tabName == "search" ? 115 : 90;
                border.Margin = new Thickness(2);
                border.Focusable = true;
                Image image = new Image();
                StackPanel sp = new StackPanel();
                sp.Margin = new Thickness(10, 11, 4, 11);
                image.Source = bs;
                border.Child = image;
                sp.Children.Add(border);
                sp.Children.Add(new Label() { HorizontalAlignment = HorizontalAlignment.Center, Content = legend.name });
                sp.MouseDown += Sp_MouseDown;
                sp.ToolTip = new ToolTip() {
                    Opacity = 0.8,
                    Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240)),
                    Placement = System.Windows.Controls.Primitives.PlacementMode.Right,
                    Content = new TextBox() {
                        BorderThickness = new Thickness(0),
                        Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(240,240,240)),
                        Text =
                        "名称：" + legend.name + "\n"+
                        "长度：" + legend.sizelong + "\n"+
                        "宽度：" + legend.width + "\n"+
                        "高度：" + legend.height + "\n"+
                        "类型：" + legend.typeName[0] + "\n"+
                        "描述：" + legend.description + "\n"
                    },
                };
                sp.Tag = file + ";" + legend.name +";"+ legend.sn + ";" + legend.typeName.Last() + ";" + legend.typeCode.Last();//记录文件位置
                pannel.Children.Add(sp);
            }));
        }
        public bool FindDwgSn(string sn)
        {
            return (bool)this.Dispatcher.Invoke(new Func<bool>(()=>{
                foreach (UIElement ui in pannel.Children)
                {
                    if (ui is StackPanel)
                    {
                        string[] tagStr = ((ui as StackPanel).Tag as string).Split(new char[] { ';' });
                        if (sn == tagStr[2])
                            return true;
                    }
                }
                return false;
            }));
        }
        public static void SetObjectAttribute(string sn)
        {
            if (sn == "door")
            {
                //s_CurrentDwgAttrib.Add("宽度", "0");
                //s_CurrentDwgAttrib.Add("厚度", "120");
                s_CurrentDwgAttrib.Add("高度", "2100");
                s_CurrentDwgAttrib.Add("镜像", "0");
            }
            else if(sn == "yakou")
            {
                //s_CurrentDwgAttrib.Add("宽度", "0");
                //s_CurrentDwgAttrib.Add("厚度", "120");
                s_CurrentDwgAttrib.Add("高度", "2100");
                s_CurrentDwgAttrib.Add("是否承重墙", "0");
            }
            else if (sn == "yanchong")
            {
                //s_CurrentDwgAttrib.Add("宽度", "0");
                //s_CurrentDwgAttrib.Add("厚度", "120");
                s_CurrentDwgAttrib.Add("高度", "2800");
            }
            else if(sn == "zhuzi")
            {
                //s_CurrentDwgAttrib.Add("宽度", "0");
                //s_CurrentDwgAttrib.Add("厚度", "120");
                s_CurrentDwgAttrib.Add("高度", "2800");
                s_CurrentDwgAttrib.Add("是否有外包口", "0");
            }
            else if (sn == "chuanghu")
            {
                //s_CurrentDwgAttrib.Add("宽度", "0");
                //s_CurrentDwgAttrib.Add("厚度", "120");
                s_CurrentDwgAttrib.Add("高度", "1400");
                s_CurrentDwgAttrib.Add("窗户类型", "1");
                s_CurrentDwgAttrib.Add("离地高度", "500");
                s_CurrentDwgAttrib.Add("深度", "0");
                s_CurrentDwgAttrib.Add("是否补光", "0");
                s_CurrentDwgAttrib.Add("是否旋转", "0");
            }
        }
        private void Sp_MouseDown(object sender, MouseButtonEventArgs e)
        {
            //DwgConvert.Cancel();
            //清空所有Thickness
            foreach (UIElement ui in pannel.Children)
                ((ui as StackPanel).Children[0] as Border).BorderThickness = new Thickness(0);
            Border border = (sender as StackPanel).Children[0] as Border;
            border.BorderThickness = new Thickness(2);

            //设置当前选中的文件
            string sTag = (sender as StackPanel).Tag as string;
            string[] sTagArray = sTag.Split(new char[] { ';' });
            DwgItem.s_CurrentDwgFile = sTagArray[0];
            DwgItem.s_CurrentDwgAttrib.Clear();
            DwgItem.s_CurrentDwgAttrib.Add("图例名称", sTagArray[1]);
            DwgItem.s_CurrentDwgAttrib.Add("图例编码", sTagArray[2]);
            DwgItem.s_CurrentDwgAttrib.Add("类型名称", sTagArray[3]);
            DwgItem.s_CurrentDwgAttrib.Add("类型编号", sTagArray[4]);
            DwgItem.s_CurrentDwgAttrib.Add("图例分类", m_TabName == "门窗" ? "硬装" : m_TabName);
            SetObjectAttribute(sTagArray[2]);
            DwgConvert.s_DmCtrl = this;
            DwgConvert.InsertBlockReference();
            //取消选中
            if (s_bCommandEnd)
                border.BorderThickness = new Thickness(0);
        }
    }
}
